import 'package:flutter/material.dart';

class EditText extends StatefulWidget {
  const EditText({super.key});

  @override
  _EditText createState() => _EditText();
}

class _EditText extends State<EditText> {
  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  late FocusScopeNode focusScopeNode;

  // 定义一个 controller
  final TextEditingController _unameController = TextEditingController();
  final TextEditingController _upAddWordController = TextEditingController();
  final GlobalKey<FormState> _globalKey = GlobalKey<FormState>(); // 明确指定为 GlobalKey<FormState>

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("输入框和表单"),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
        child: Form(
          key: _globalKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            children: <Widget>[
              TextFormField(
                autofocus: true,
                controller: _unameController,
                decoration: InputDecoration(
                  labelText: "用户名",
                  hintText: "用户名或邮箱",
                  icon: Icon(Icons.person),
                ),
                // 校验用户名
                validator: (v) {
                  return v!.trim().isNotEmpty ? null : "用户名不能为空";
                },
              ),
              TextFormField(
                controller: _upAddWordController,
                decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "您的登录密码",
                  icon: Icon(Icons.lock),
                ),
                obscureText: true,
                // 校验密码
                validator: (v) {
                  return v!.trim().length > 5 ? null : "密码不能少于6位";
                },
              ),
              Padding(
                padding: const EdgeInsets.only(top: 28.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          foregroundColor: Colors.white,
                          backgroundColor: Theme.of(context).primaryColor,
                          padding: EdgeInsets.all(15.0),
                        ),
                        child: Text("登录"),
                        onPressed: () {
                          // 调用 validate 方法校验表单
                          if (_globalKey.currentState!.validate()) {
                            // 验证通过提交数据
                            print("输入的数据符合要求,可以提交");
                          }
                        },
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
